package com.zh.zuul.filter;


import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.exception.ZuulException;
import com.zh.zuul.dao.IPTableMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

/**
 * code is far away from bug with the animal protecting
 * ┏┓　　　┏┓
 * ┏┛┻━━━┛┻┓
 * ┃　　　　　　　┃
 * ┃　　　━　　　┃
 * ┃　┳┛　┗┳　┃
 * ┃　　　　　　　┃
 * ┃　　　┻　　　┃
 * ┃　　　　　　　┃
 * ┗━┓　　　┏━┛
 * 　　┃　　　┃神兽保佑
 * 　　┃　　　┃代码无BUG！
 * 　　┃　　　┗━━━┓
 * 　　┃　　　　　　　┣┓
 * 　　┃　　　　　　　┏┛
 * 　　┗┓┓┏━┳┓┏┛
 * 　　　┃┫┫　┃┫┫
 * 　　　┗┻┛　┗┻┛
 *
 * @Description: 防火墙过滤
 * @Author: Li.HuiNeng
 * @Create in: 2019-09-21 10:19
 * @Version: 1.0.1
 */
@Component
public class FirewallFilter extends ZuulFilter {


    // 最先执行登录过滤器
    private static final int FIREWALL_ORDER = 0;

    @Autowired
    private IPTableMapper ipTableMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    private Logger log = LoggerFactory.getLogger(FirewallFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return FIREWALL_ORDER;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * @Description: 客户端ip拦截过滤
     * ------------------------
     * @Author: Li.HuiNeng
     * @Date: 2019/9/21
     */
    @Override
    public Object run() throws ZuulException {
       /* AtomicBoolean boolF = new AtomicBoolean(false);
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        // 获取请求ip地址
        String ip = IpAddressUtil.getIpAddress(request);
        List<IPTableEntity> list = new ArrayList<>();
        if (redisTemplate.opsForValue().get(HttpResMsgDes.REDIS_IP_LIST_KEY) == null) {
            list = ipTableMapper.selectList(new QueryWrapper<IPTableEntity>().eq("status", 1));
            redisTemplate.opsForValue().set(HttpResMsgDes.REDIS_IP_LIST_KEY, list, 15, TimeUnit.DAYS);
        } else {
            list = (List<IPTableEntity>)redisTemplate.opsForValue().get(HttpResMsgDes.REDIS_IP_LIST_KEY);
        }
        // 获取数据库中存储的ip,存在放行
        list.forEach( o -> {
            if (o.getIp().equals(ip)) boolF.set(true);
        });
        if (boolF.get()) {
            return null;
        } else {
            log.warn("来自{}客户端ip未授权访问!", ip);
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(416);
            try {
                context.getResponse().sendError(HttpStatus.REQUESTED_RANGE_NOT_SATISFIABLE.value(), "您的ip被锁定，请找管理人员解锁!");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }*/
        return null;
    }
}
